﻿<%@ WebHandler Language="C#" Class="GoodsHandler" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using StarTech.DBUtility;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Web.DynamicData;
using StarTech.Order.Order;
using StarTech.Order;


public class GoodsHandler : IHttpHandler
{
    AdoHelper ado = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string flag = Common.NullToEmpty(context.Request["flag"]);
        //查询条件searchfilter,前台须encode下
        string searchfilter = Common.NullToEmpty(context.Request["searchfilter"]);

        //jggrid内部参数rows=10&page=2&sidx=id&sord=desc
        string rows = Common.NullToEmpty(context.Request["rows"], "15");     //显示数量
        string page = Common.NullToEmpty(context.Request["page"], "1");      //当前页
        string sidx = Common.NullToEmpty(context.Request["sidx"], "GoodsId");       //排序字段
        string sord = Common.NullToEmpty(context.Request["sord"], "");   //排序规则

        //任务信息
        string goodsId = Common.NullToEmpty(context.Request["gid"]);
        string jobStartTime = Common.NullToEmpty(context.Request["jobStartTime"]);
        int jobDay = Common.NullToZero(context.Request["jobDay"]);
        int jobArea = Common.NullToZero(context.Request["jobArea"]);
        string categoryId = Common.NullToEmpty(context.Request["categoryId"]);
        string goodsName = Common.NullToEmpty(context.Request["goodsName"]);
        string goodsDesc = Common.NullToEmpty(context.Request["goodsDesc"]);
        string salePrice = Common.NullToEmpty(context.Request["salePrice"]);
        string jobNeeds = Common.NullToEmpty(context.Request["jobNeeds"]);
        string jobType = Common.NullToEmpty(context.Request["jobType"]);
        string jobAddress = Common.NullToEmpty(context.Request["jobAddress"]);
        int isSale = Common.NullToZero(context.Request["isSale"] == null ? "1" : context.Request["isSale"]);
        string picIds = Common.NullToEmpty(context.Request["picIds"]);
        string id = Common.NullToEmpty(context.Request["id"]);
        int status = Common.NullToZero(context.Request["status"]);


        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
        }


        switch (flag.ToLower())
        {
            case "list":
                context.Response.Write(GetGoodsList(categoryId, jobType));
                break;
            case "mylist":
                context.Response.Write(GetMyGoodsList(jobType));
                break;
            case "myacceptlist":
                context.Response.Write(MyAcceptList(jobType, status));
                break;
            case "info":
                context.Response.Write(GetGoodsInfo(goodsId));
                break;
            case "infodetail":
                context.Response.Write(GetGoodsInfoDetail(goodsId));
                break;
            case "add":
                context.Response.Write(AddGoodsInfo(jobStartTime, jobDay, jobArea, categoryId, goodsName, goodsDesc, salePrice, jobNeeds, jobAddress, jobType, isSale, picIds));
                break;
            case "update":
                context.Response.Write(UpdateGoodsInfo(goodsId, jobStartTime, jobDay, jobArea, categoryId, goodsName, goodsDesc, salePrice, jobNeeds, jobAddress, isSale, picIds));
                break;
            case "getcate":
                context.Response.Write(getCategory());
                break;
            case "uppic":
                if (context.Request.Files.Count == 0)
                {
                    context.Response.Write("请选择文件");  //代表文件为空
                }
                else
                {
                    context.Response.Write(UploadFile(context.Request.Files[0]));
                }
                break;
            case "delpic":
                context.Response.Write(DeletePic(id));
                break;
        }
    }

    private string MyAcceptList(string jobType, int status)
    {
        string filter = "";
        if (status == 0)
        {
            filter = " and (d.iscomplete is null or d.iscomplete='0') ";
        }
        else
        {
            filter = " and d.iscomplete='1' ";
        }
        string json = "";
        string strSql = @"select g.commentId,d.OrderId,a.PriceId,b.GoodsId,b.GoodsName,a.MemberPrice,b.JobNeeds,c.CategoryName,b.JobAddress,b.JobStatus,b.JobType,a.JobStartTime,a.JobEndTime,a.IsEmployerSelect,a.IsMemberConfirm,d.IsPay,d.OrderAllMoney from T_Goods_MemberPrice a
            left join T_Goods_Info b on a.GoodsId=b.GoodsId
            left join T_Info_Category c on b.CategoryId=c.CategoryId
            left join T_Order_Info d on a.PriceId=d.PriceId
            left join T_Order_InfoDetail e on d.OrderId=e.OrderId
            left join T_Order_Comment g on d.OrderId=g.OrderId and g.createMemberId=@memberId
            where a.IsLast=1 and a.MemberId=@memberId and b.JobType=@JobType " + filter + " order by a.MemberConfirmTime desc";
        SqlParameter[] parameters = { new SqlParameter("@memberId", memberId), new SqlParameter("@JobType", jobType) };

        DataTable dt = ado.ExecuteSqlDataset(strSql, parameters).Tables[0];
        json = JSONHelper.GetJSON(dt);
        return json;
    }

    private string GetGoodsList(string categoryId, string jobType)
    {
        string json = "";
        string strSql = @"select GoodsId,a.CategoryId,b.CategoryName,GoodsName,GoodsCode,GoodsDesc,SalePrice,AddTime,ProviderInfo,JobStartTime,JobEndTime,JobDay,JobNeeds,JobAddress,JobType,JobStatus,IsSale,GoodsSmallPic from T_Goods_Info a left join T_Info_Category b on a.CategoryId=b.CategoryId where JobStartTime>='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and (JobStatus='竞价中' or JobStatus='进行中') ";
        strSql += " and jobType='" + jobType + "' and JobStartTime>'" + DateTime.Now.ToString() + "'";
        if (jobType.Equals("QB"))
        {
            strSql += " and goodsId not in (select goodsid from T_Order_InfoDetail)";
        }

        DataTable dt = new DataTable();
        if (string.IsNullOrEmpty(categoryId))
        {
            strSql += " order by AddTime desc ";
            dt = ado.ExecuteSqlDataset(strSql).Tables[0];
        }
        else
        {
            strSql += " and a.CategoryId=@categoryId order by AddTime desc";
            SqlParameter[] p = new SqlParameter[] {
                new SqlParameter("@categoryId",categoryId)
            };
            dt = ado.ExecuteSqlDataset(strSql, p).Tables[0];
        }
        foreach (DataRow row in dt.Rows)
        {
            if (row["GoodsSmallPic"].ToString() == "") { row["GoodsSmallPic"] = "/AppClient/Images/nopic.jpg"; }
        }

        json += JSONHelper.GetJSON(dt);
        return json;
    }

    private string GetMyGoodsList(string jobType)
    {
        string json = "";
        string strSql = @"select a.GoodsId,GoodsName,GoodsCode,AddTime,JobStatus,ISNULL(b.priceCount,0) as priceCount from T_Goods_Info a
            left join (select GoodsId,COUNT(1) as priceCount from (select GoodsId from T_Goods_MemberPrice group by MemberId,GoodsId) t group by GoodsId) b on a.GoodsId=b.GoodsId where 1=1 ";
        strSql += " and a.jobType=@jobType and a.ProviderInfo=@MemberId and a.JobStatus<>'已结束' order by AddTime desc";

        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@jobType",jobType),
            new SqlParameter("@MemberId",memberId)
        };
        DataTable dt = new DataTable();
        dt = ado.ExecuteSqlDataset(strSql, p).Tables[0];
        json += JSONHelper.GetJSON(dt);
        return json;
    }

    private string GetGoodsInfo(string goodsId)
    {
        string json = "";

        string strSql = @"select GoodsId,a.CategoryId,b.CategoryName,GoodsName,GoodsCode,GoodsDesc,SalePrice,AddTime,ProviderInfo,JobStartTime,JobEndTime,JobDay,JobArea,JobNeeds,JobAddress,JobType,JobStatus,IsSale from T_Goods_Info a left join T_Info_Category b on a.CategoryId=b.CategoryId where a.GoodsId=@GoodsId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@GoodsId",goodsId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
        json += "_$$_";
        string strSql2 = @"select sysnumber,picPath,picType from T_Goods_Pic where GoodsId=@GoodsId and PicType='GC' order by orderby";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@GoodsId",goodsId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql2, p2).Tables[0]);
        return json;
    }

    private string GetGoodsInfoDetail(string goodsId)
    {
        string json = "";

        string strSql = @"select GoodsId,a.CategoryId,b.CategoryName,GoodsName,GoodsCode,GoodsDesc,SalePrice,AddTime,ProviderInfo,JobStartTime,JobEndTime,JobDay,JobArea,JobNeeds,JobAddress,JobType,JobStatus,IsSale,c.MemberId,c.TrueName,c.Mobile from T_Goods_Info a 
                left join T_Info_Category b on a.CategoryId=b.CategoryId 
                left join T_Member_Info c on a.ProviderInfo=c.MemberId where a.GoodsId=@GoodsId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@GoodsId",goodsId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
        json += "_$$_";
        string strSql2 = @"select sysnumber,picPath,picType from T_Goods_Pic where GoodsId=@GoodsId and PicType='GC' order by orderby";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@GoodsId",goodsId)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql2, p2).Tables[0]);
        return json;
    }

    private string AddGoodsInfo(string jobStartTime, int jobDay, int jobArea, string categoryId, string goodsName, string goodsDesc, string salePrice, string jobNeeds, string jobAddress, string jobType, int isSale, string picIds)
    {
        try
        {
            string goodsId = IdCreator.CreateId("T_Goods_Info", "GoodsId");
            string goodsCode = IdCreator.CreateId("T_Goods_Info", "GoodsCode");

            string goodsSmallPic = UpdatePicInfo(goodsId, picIds);

            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into T_Goods_Info(");
            strSql.Append("GoodsId,CategoryId,GoodsName,GoodsCode,GoodsDesc,SalePrice,AddTime,ProviderInfo,JobStartTime,JobEndTime,JobDay,JobArea,JobNeeds,JobAddress,JobType,JobStatus,IsSale,GoodsSmallPic)");
            strSql.Append(" values (");
            strSql.Append("@GoodsId,@CategoryId,@GoodsName,@GoodsCode,@GoodsDesc,@SalePrice,@AddTime,@ProviderInfo,@JobStartTime,@JobEndTime,@JobDay,@JobArea,@JobNeeds,@JobAddress,@JobType,@JobStatus,@IsSale,@GoodsSmallPic)");
            SqlParameter[] parameters = {
                new SqlParameter("@GoodsId",goodsId),
                new SqlParameter("@CategoryId",categoryId),
                new SqlParameter("@GoodsName",goodsName),
                new SqlParameter("@GoodsCode",goodsCode),
                new SqlParameter("@GoodsDesc",goodsDesc),
                new SqlParameter("@SalePrice",salePrice),
                new SqlParameter("@AddTime",DateTime.Now.ToString()),
                new SqlParameter("@ProviderInfo",memberId),
                new SqlParameter("@JobStartTime",jobStartTime),
                new SqlParameter("@JobEndTime",Convert.ToDateTime(jobStartTime).AddDays(Convert.ToInt32(jobDay)).ToString()),
                new SqlParameter("@JobDay",jobDay),
                new SqlParameter("@JobArea",jobArea),
                new SqlParameter("@JobNeeds",jobNeeds),
                new SqlParameter("@JobAddress",jobAddress),
                new SqlParameter("@JobType",jobType),
                new SqlParameter("@JobStatus",isSale==1?"竞价中":"未发布"),
                new SqlParameter("@IsSale",isSale),
                new SqlParameter("@GoodsSmallPic",goodsSmallPic)
            };
            ado.ExecuteSqlNonQuery(strSql.ToString(), parameters);


            return Common.AddLogMsg(memberId, "任务发布成功", "您的【" + goodsName + "】任务已经发布成功，可在个人中心我的" + (jobType.Equals("QB") ? "发包" : "招工") + "任务中查看", "MyTask" + (jobType.Equals("QB") ? "" : "People") + "List.html", 0);
        }
        catch (Exception ex)
        { return "错误：" + ex.Message; }
    }

    private string UpdateGoodsInfo(string goodsId, string jobStartTime, int jobDay, int jobArea, string categoryId, string goodsName, string goodsDesc, string salePrice, string jobNeeds, string jobAddress, int isSale, string picIds)
    {
        try
        {
            string goodsSmallPic = UpdatePicInfo(goodsId, picIds);

            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_Goods_Info set ");
            strSql.Append("CategoryId=@CategoryId,GoodsName=@GoodsName,GoodsDesc=@GoodsDesc,SalePrice=@SalePrice,JobStartTime=@JobStartTime,JobEndTime=@JobEndTime,JobDay=@JobDay,JobArea=@JobArea,JobNeeds=@JobNeeds,JobAddress=@JobAddress,GoodsSmallPic=@GoodsSmallPic");
            if (isSale == 1)
                strSql.Append(",IsSale=@IsSale");
            strSql.Append(" where GoodsId=@GoodsId");
            SqlParameter[] parameters = {
                new SqlParameter("@GoodsId",goodsId),
                new SqlParameter("@CategoryId",categoryId),
                new SqlParameter("@GoodsName",goodsName),
                new SqlParameter("@GoodsDesc",goodsDesc),
                new SqlParameter("@SalePrice",salePrice),
                new SqlParameter("@JobStartTime",jobStartTime),
                new SqlParameter("@JobEndTime",Convert.ToDateTime(jobStartTime).AddDays(Convert.ToInt32(jobDay)).ToString()),
                new SqlParameter("@JobDay",jobDay),
                new SqlParameter("@JobArea",jobArea),
                new SqlParameter("@JobNeeds",jobNeeds),
                new SqlParameter("@JobAddress",jobAddress),
                new SqlParameter("@IsSale",isSale),
                new SqlParameter("@GoodsSmallPic",goodsSmallPic)
            };
            ado.ExecuteSqlNonQuery(strSql.ToString(), parameters);
            return goodsId;
        }
        catch (Exception ex)
        { return "错误：" + ex.Message; }
    }

    private string UpdatePicInfo(string goodsId, string picIds)
    {
        string[] picIdArray = picIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        string upPicSql = "update t_goods_pic set GoodsId='" + goodsId + "' where Sysnumber=@Sysnumber and MemberId=@MemberId;";
        int result = 0;
        for (int i = 0; i < picIdArray.Length; i++)
        {
            IDataParameter[] p = new IDataParameter[]
            {
                    new SqlParameter("@Sysnumber",picIdArray[i]),
                    new SqlParameter("@MemberId",memberId)
            };
            result += ado.ExecuteSqlNonQuery(upPicSql, p);
        }

        if (picIdArray.Length > 0)
        {
            string strSql = "select top 1 picpath from t_goods_pic where Sysnumber=@Sysnumber and MemberId=@MemberId;";
            IDataParameter[] p = new IDataParameter[]
            {
                    new SqlParameter("@Sysnumber",picIdArray[0]),
                    new SqlParameter("@MemberId",memberId)
            };
            return ado.ExecuteSqlScalar(strSql, p).ToString();
        }
        else
        {
            //添加默认照片
            string path = "/upload/goods";
            path += "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/";
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
            path += DateTime.Now.ToString("HHmmssffff") + ".jpg";
            File.Copy(HttpContext.Current.Server.MapPath("/AppClient/Images/Banner.jpg"), HttpContext.Current.Server.MapPath(path));

            //修改数据库
            string id = Guid.NewGuid().ToString();
            string strSql = string.Format("insert into t_goods_pic(Sysnumber, PicPath, Orderby, PicType,GoodsId, MemberId) values(@Sysnumber,@PicPath,@Orderby,@PicType,@GoodsId,@MemberId)");
            SqlParameter[] p = new SqlParameter[]
            {
                new SqlParameter("@Sysnumber",id),
                new SqlParameter("@PicPath",path),
                new SqlParameter("@Orderby","0"),
                new SqlParameter("@PicType","GC"),
                new SqlParameter("@GoodsId",goodsId),
                new SqlParameter("@MemberId",memberId),
            };
            ado.ExecuteSqlNonQuery(strSql, p);

            return "";
        }
    }

    private string UploadFile(HttpPostedFile file)
    {
        string fileTail = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
        if (fileTail != ".jpeg" && fileTail != ".jpg" && fileTail != ".png" && fileTail != ".bmp" && fileTail != ".gif")
        {
            return "图片格式不正确";
        }
        if (file.ContentLength > 10240000)
        {
            return "图片不能大于10M";
        }

        //保存文件
        string path = "/upload/goods";
        path += "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/";
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
        path += DateTime.Now.ToString("HHmmssffff") + fileTail;
        file.SaveAs(HttpContext.Current.Server.MapPath(path));



        //缩略图
        string smallPath = path.Replace(fileTail, "_s" + fileTail);
        bool iscreate = MakeSmallPic(HttpContext.Current.Server.MapPath(path), HttpContext.Current.Server.MapPath(smallPath));
        if (iscreate == false) { smallPath = path; }

        //修改数据库
        string id = Guid.NewGuid().ToString();
        string strSql = string.Format("insert into t_goods_pic(Sysnumber, PicPath, Orderby, PicType,GoodsId, MemberId) values(@Sysnumber,@PicPath,@Orderby,@PicType,@GoodsId,@MemberId)");
        SqlParameter[] p = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber",id),
            new SqlParameter("@PicPath",smallPath),
            new SqlParameter("@Orderby","0"),
            new SqlParameter("@PicType","GC"),
            new SqlParameter("@GoodsId",""),
            new SqlParameter("@MemberId",memberId),
        };
        ado.ExecuteSqlNonQuery(strSql, p);
        return id + "_$$_" + smallPath;
    }




    protected bool MakeSmallPic(string oldPicPath, string smallPicPath)
    {
        try
        {
            System.Threading.Thread.Sleep(1000);
            WLWang.MakeThumbnail.MakeToThumbnail(oldPicPath, smallPicPath, 400, 300, "Cut");
            return true;
            // 生成缩略图方法 
            //生成的缩略图稍微比前台显示的图片大点，这样显示的清晰度高点（如前台显示100*150，则生成200*300）
        }
        catch { return false; }
    }

    private string DeletePic(string id)
    {
        string strSql1 = "select picpath from t_goods_pic where Sysnumber=@Sysnumber and MemberId=@MemberId;";
        SqlParameter[] p1 = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber", id),
            new SqlParameter("@MemberId",memberId),
        };
        string picpath = ado.ExecuteSqlScalar(strSql1, p1).ToString();
        File.Delete(HttpContext.Current.Server.MapPath(picpath));

        string strSql2 = "delete from t_goods_pic where Sysnumber=@Sysnumber and MemberId=@MemberId;";
        SqlParameter[] p2 = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber", id),
            new SqlParameter("@MemberId",memberId),
        };
        return ado.ExecuteSqlNonQuery(strSql2, p2).ToString();
    }

    private string getCategory()
    {
        string strSql = "select CategoryId,CategoryName from T_Info_Category order by Orderby";
        DataTable dt = ado.ExecuteSqlDataset(strSql).Tables[0];
        return JSONHelper.GetJSON(dt);
    }

    /// <summary>
    /// 订单主表T_Order_Info
    /// </summary>
    protected string UpdateOrder(string PriceId, string OrderId)
    {
        //读取报价表和其他信息
        //报价表
        SqlParameter[] parameters =
        {
            new SqlParameter("@priceId", PriceId)
        };
        DataTable dtPrice = ado.ExecuteSqlDataset("select * from T_Goods_MemberPrice where PriceId=@priceId", parameters).Tables[0];
        if (dtPrice.Rows.Count == 0) { return ""; }
        string MemberId = dtPrice.Rows[0]["MemberId"].ToString();       //（重要）雇员编号
        string GoodsId = dtPrice.Rows[0]["GoodsId"].ToString();         //（重要）工程信息编号
        decimal OrderAllMoney = decimal.Parse(dtPrice.Rows[0]["MemberPrice"].ToString());     //（重要）订单价格
        string Tel = dtPrice.Rows[0]["MemberMobile"].ToString();

        //会员表
        DataTable dtMember = ado.ExecuteSqlDataset("select * from T_Member_Info where MemberId='" + MemberId + "'").Tables[0];
        if (dtMember.Rows.Count == 0) { return ""; }
        string MemberName = dtMember.Rows[0]["MemberName"].ToString();
        string TrueName = dtMember.Rows[0]["TrueName"].ToString();
        string AddressCode = dtMember.Rows[0]["AddressCode"].ToString();
        string AddressDetail = dtMember.Rows[0]["AddressDetail"].ToString();
        string PostCode = dtMember.Rows[0]["PostCode"].ToString();

        //工程需求信息表
        DataTable dtGoods = ado.ExecuteSqlDataset("select * from T_Goods_Info where GoodsId='" + GoodsId + "'").Tables[0];
        if (dtGoods.Rows.Count == 0) { return ""; }
        string SellerId = dtGoods.Rows[0]["ProviderInfo"].ToString();    //（重要）雇主编号
        string JobType = dtGoods.Rows[0]["JobType"].ToString();          //（重要）订单类型，和工作类型关联：全包（QB）、钟点工（DG）


        //订单主表（订单主信息，包括人员信息和价格信息等）
        ModOrder mod = new ModOrder();

        //订单基本信息
        mod.OrderId = OrderId;
        mod.OrderType = JobType;                                         //（重要）订单类型，和工作类型关联：全包（QB）、钟点工（DG）
        mod.OrderTime = DateTime.Now;
        mod.SendMethod = "off";
        mod.PayMethod = "在线支付";


        //雇员信息
        mod.MemberId = MemberId;                                        //（重要）雇员编号
        mod.MemberName = MemberName;
        mod.MemberOrderRemarks = "";                                    //订单备注（备用）
        mod.ReceivePerson = TrueName;
        mod.ReceiveAddressCode = AddressCode;
        mod.ReceiveAddressDetail = AddressDetail;
        mod.Tel = Tel;
        mod.PostCode = PostCode;

        //雇主信息
        mod.SellerId = SellerId;                                        //（重要）雇主编号

        //价格信息
        mod.OrderAllMoney = OrderAllMoney;                              //（重要）订单价格
        mod.GoodsAllMoney = OrderAllMoney;
        mod.OrderAllWeight = 0;
        mod.OrderAllWeight = 0;

        //支付信息
        mod.IsPay = 0;                                                  //（重要）是否支付
        mod.PayInterfaceCode = "";                                      //第三方支付接口提交的编号，查账用
        mod.PayMethod = "";                                             //支付方式（支付宝ZFB，微信WX等）
        mod.PayTime = DateTime.Now;                                     //支付时间

        mod.priceId = PriceId;

        //创建订单
        if (new BllOrder().Update(mod) > 0)
        {
            //明细信息
            UpdateOrderDetail(mod.OrderId, mod.OrderType, GoodsId);
        }

        return mod.OrderId;
    }


    /// <summary>
    /// 订单明细T_Order_InfoDetail
    /// </summary>
    protected int UpdateOrderDetail(string OrderId, string OrderType, string GoodsId)
    {
        DataTable dt = ado.ExecuteSqlDataset("select * from T_Goods_Info where GoodsId='" + GoodsId + "'").Tables[0];
        BllOrderDetail bllDetail = new BllOrderDetail();
        int i = 0;
        if (dt.Rows.Count > 0)
        {
            DataTable dt2 = ado.ExecuteSqlDataset("select sysnumber from T_Order_InfoDetail where GoodsId='" + GoodsId + "'").Tables[0];
            DataRow row = dt.Rows[0];
            foreach (DataRow row2 in dt2.Rows)
            {
                ModOrderDetail mod = new ModOrderDetail();
                mod.sysnumber = row2["sysnumber"].ToString();
                mod.OrderId = OrderId;
                mod.OrderType = OrderType;
                mod.GoodsId = row["GoodsId"].ToString();
                mod.GoodsName = row["GoodsName"].ToString();
                mod.GoodsCode = row["GoodsCode"].ToString();
                mod.GoodsFormate = row["GoodsFormate"].ToString();
                mod.Price = decimal.Parse(row["SalePrice"].ToString());
                mod.GoodsPic = row["GoodsSmallPic"].ToString();
                mod.ProviderInfo = row["ProviderInfo"].ToString();
                mod.DataFrom = row["DataFrom"].ToString();
                mod.Quantity = 1;
                mod.AllMoney = mod.Price * mod.Quantity;
                mod.AllWeight = mod.OneWeight * mod.Quantity;
                i += bllDetail.Update(mod);
            }
        }
        return i;
    }


    /// <summary>
    /// 获取所有任务 
    /// </summary>
    /// <param name="curPage"></param>
    /// <param name="pageSize"></param>
    /// <param name="orderBy"></param>
    /// <param name="orderByRole"></param>
    /// <returns></returns>
    public string List(string curPage, string pageSize, string orderBy, string orderByRole)
    {
        string table = " T_Goods_Info ";
        string fields = " GoodsId as gid,Goodscode as gcode ,CategoryId,GoodsName as gname,GoodsSmallPic as gpic";
        string filter = GetFilter();
        string sort = " order by " + orderBy + " " + orderByRole + "";
        int totalRecords = 0;
        DataTable dtSource = new PaginationUtility().GetPaginationList(fields, table, filter, sort, Int32.Parse(curPage), Int32.Parse(pageSize), out totalRecords);

        int totalPages = JSONHelper.GetTotalPages(totalRecords, Int32.Parse(pageSize));
        EditDataSource(ref dtSource, curPage, totalPages, totalRecords);
        return JSONHelper.GetJSON(dtSource);


    }

    /// <summary>
    /// 根据关键字获取数据 含分页
    /// </summary>
    /// <param name="curPage"></param>
    /// <param name="pageSize"></param>
    /// <param name="orderBy"></param>
    /// <param name="orderByRole"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    private string GetGoodsByKey(string curPage, string pageSize, string orderBy, string orderByRole, string key)
    {
        string table = " T_Goods_Info ";
        string fields = " GoodsId as gid,Goodscode as gcode ,CategoryId,GoodsName as gname,GoodsSmallPic as gpic";
        string filter = GetFilter();
        string sort = " order by " + orderBy + " " + orderByRole + "";
        int totalRecords = 0;
        DataTable dtSource = new PaginationUtility().GetPaginationList(fields, table, filter, sort, Int32.Parse(curPage), Int32.Parse(pageSize), out totalRecords);

        int totalPages = JSONHelper.GetTotalPages(totalRecords, Int32.Parse(pageSize));
        EditDataSource(ref dtSource, curPage, totalPages, totalRecords);
        return JSONHelper.GetJSON(dtSource);

    }


    /// <summary>
    /// 获取查询条件
    /// </summary>
    /// <returns></returns>
    public string GetFilter()
    {
        string filter = " 1=1 and IsSale=1 ";

        return filter;
    }

    /// <summary>
    /// 编辑数据源
    /// </summary>
    /// <param name="dt"></param>
    private void EditDataSource(ref DataTable dt, string curpage, int totalpage, int totalrecords)
    {
        dt.Columns.Add("curpage", typeof(string));
        dt.Columns.Add("totalpage", typeof(string));
        dt.Columns.Add("totalrecords", typeof(string));
        foreach (DataRow dr in dt.Rows)
        {
            dr["curpage"] = curpage.ToString();
            dr["totalpage"] = totalpage.ToString();
            dr["totalrecords"] = totalrecords.ToString();
        }
    }



    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}